<?php

declare(strict_types=1);

namespace app\works;

use owns\enum\RespCode;

class WorkTool
{
    /**
     * @param array|string|integer $data 内容
     * @param integer $mcode 消息分类编码
     * @param string $msg
     */
    public static function success($data = '', $mcode = 1000, $msg = 'success')
    {
        return json_encode(['code' => RespCode::SUCCESS, 'data' => $data, 'msg' => $msg, 'mcode' => $mcode]);
    }
    /**
     * @param string $msg
     * @param array|string|integer $data
     * @param integer $mcode 消息分类编码
     */
    public static function error($msg = 'error', $data = '', $mcode = 1000)
    {
        return json_encode(['code' => RespCode::ERROR, 'msg' => $msg, 'data' => $data, 'mcode' => $mcode]);
    }

    /**
     * 执行推送
     * @param array $data
     * @return array
     */
    private static function push(array $data)
    {
        $socket = stream_socket_client('tcp://127.0.0.1:9522', $error, $msg, 1);
        fwrite($socket, json_encode($data) . "\n");
        $result = fread($socket, 8192);
        fclose($socket);
        return $result;
    }
    /**
     * 群推
     * @param string $code 消息类型
     * @param integer $send_id 推送人id
     * @param array $data 数据
     * @param string $send_receive 发送是否接收通知: 0否 1是
     */
    public static function crowd(int $code, int $send_id, array $data, int $send_receive = 0)
    {
        $data = [
            'code' => $code, 'send_id' => $send_id, 'receive_id' => 0,
            'message' => $data, 'send_receive' => $send_receive
        ];
        self::push($data);
    }
    /**
     * 指定推送
     * @param string $code 消息类型
     * @param integer $send_id 推送人id
     * @param integer $receive_id 接收人id
     * @param array $data 数据
     */
    public static function general(int $code, int $send_id, int $receive_id, array $data)
    {
        $data = [
            'code' => $code, 'send_id' => $send_id, 'receive_id' => $receive_id,
            'message' => $data,
        ];
        self::push($data);
    }
}
